import { NextResponse } from "next/server"; import { z } from "zod"; import { apiError, parseBody } from "@/lib/api.ts"; import { assertSameOrigin, requireUser } from "@/lib/auth/session.ts"; import { all, get, run } from "@/lib/db/index.ts"; async function owned(id: number, userId: number) { const conv = get<{ id: number }>("SELECT id FROM conversations WHERE id = ? AND user_id = ?", id, userId); if (!conv) throw Object.assign(new Error("Conversation introuvable."), { status: 404 }); return conv; } export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) { try { const user = await requireUser(); const id = parseInt((await ctx.params).id, 10); await owned(id, user.id); const conversation = get("SELECT * FROM conversations WHERE id = ?", id); const messages = all( "SELECT id, role, content, citations, attachments, tool_trace, model, mode, knowledge_mode, feedback, flagged, saved, created_at FROM messages WHERE conversation_id = ? ORDER BY id", id ); return NextResponse.json({ conversation, messages }); } catch (e) { return apiError(e); } } const patchSchema = z.object({ title: z.string().min(1).max(200).optional(), folder: z.string().max(100).optional(), pinned: z.boolean().optional(), archived: z.boolean().optional(), }); export async function PATCH(req: Request, ctx: { params: Promise<{ id: string }> }) { try { await assertSameOrigin(); const user = await requireUser(); const id = parseInt((await ctx.params).id, 10); await owned(id, user.id); const body = await parseBody(req, patchSchema); if (body.title !== undefined) run("UPDATE conversations SET title = ? WHERE id = ?", body.title, id); if (body.folder !== undefined) run("UPDATE conversations SET folder = ? WHERE id = ?", body.folder, id); if (body.pinned !== undefined) run("UPDATE conversations SET pinned = ? WHERE id = ?", body.pinned ? 1 : 0, id); if (body.archived !== undefined) run("UPDATE conversations SET archived = ? WHERE id = ?", body.archived ? 1 : 0, id); return NextResponse.json({ ok: true }); } catch (e) { return apiError(e); } } export async function DELETE(_req: Request, ctx: { params: Promise<{ id: string }> }) { try { await assertSameOrigin(); const user = await requireUser(); const id = parseInt((await ctx.params).id, 10); await owned(id, user.id); run("DELETE FROM conversations WHERE id = ?", id); return NextResponse.json({ ok: true }); } catch (e) { return apiError(e); } }